﻿using System;
using System. Windows. Threading;
using System. Collections. Generic;
using System. Net;
using NextApp. WP7. Models;
using System. IO. IsolatedStorage;
using System. Linq;

namespace NextApp. WP7. Cache. Base
{
	public abstract class CacheBase
	{
		#region 属性
		/// <summary>
		/// 计时器
		/// </summary>
		protected DispatcherTimer timer
		{
			get;
			private set;
		}

		/// <summary>
		/// 定期清空数据的计时器
		/// </summary>
		protected DispatcherTimer timer_Clear
		{
			get;
			private set;
		}

		/// <summary>
		/// 任务队列
		/// </summary>
		protected Queue<AsyncMissionBase> Missions
		{
			get;
			private set;
		}
		public void Enqueue(AsyncMissionBase mission)
		{
			System. Diagnostics. Debug. WriteLine("缓存入队: {0}", mission. queryStringWithUrl);
			this. Missions. Enqueue(mission);
		}

		#endregion

		#region 初始化
		public virtual void Initialize(TimeSpan idleTime)
		{
			this. Missions = new Queue<AsyncMissionBase>( );
			this. timer = new DispatcherTimer { Interval = idleTime };
			this. timer. Tick += new EventHandler(timer_Tick);
			this. timer. Start( );
		}
		#endregion

		#region LifeCycle
		private void timer_Tick(object sender, EventArgs e)
		{
			//当两个条件都满足了才处理
			if ( this.Missions.Count > 0 )
			{
				AsyncMissionBase newMission = this. Missions. Dequeue( );
				if (null != newMission )
				{
					System. Diagnostics. Debug. WriteLine("处理出队元素 {0}", newMission. queryStringWithUrl);
					this. ProcessThisMission(newMission);
				}
			}
		}

		protected abstract void ProcessThisMission(AsyncMissionBase mission);
		#endregion
	}
}
